package com.tanchengjin.admin.modules.blog.controller.api.v1;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tanchengjin.admin.model.dao.UserMapper;
import com.tanchengjin.admin.model.pojo.User;
import com.tanchengjin.admin.modules.blog.utils.JWTUtil;
import com.tanchengjin.admin.utils.ServerResponse;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户相关")
@Controller
@RequestMapping(value = "/api/v1/user")
public class UserApiController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/info")
    @ResponseBody
    public ServerResponse userinfo(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization.startsWith("Bearer ")) {
            String[] s = authorization.split(" ");
            String token = s[1];
            if (!JWTUtil.verify(token)) {
                return ServerResponse.responseWithFailureMessage("token错误");
            }
            DecodedJWT decode = JWT.decode(token);
            String uid = decode.getClaim("uid").asString();
            User user = userMapper.selectByPrimaryKey(Long.valueOf(uid));
            user.setPassword(null);
            return ServerResponse.responseWithSuccess(user);
        } else {
            return ServerResponse.responseWithFailureMessage("token错误");
        }
    }

//    @RequestMapping(value = "/test", method = RequestMethod.GET)
//    @ResponseBody
//    public ServerResponse test(Authentication authentication) {
////        Object credentials = authentication.getCredentials();
////        OAuth2AuthenticationDetails credentials1 = (OAuth2AuthenticationDetails) authentication.getDetails();
////        String token = credentials1.getTokenValue();
////        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
////        objectObjectHashMap.put("token",token);
////        objectObjectHashMap.put("er", credentials1.getRemoteAddress());
////        objectObjectHashMap.put("er3", credentials1.getDecodedDetails());
////        objectObjectHashMap.put("er32", credentials1.getSessionId());
////        objectObjectHashMap.put("er33", credentials1.getTokenType());
////        return ServerResponse.responseWithSuccess(objectObjectHashMap);
//    }
}
